package com.example.security.util;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

import org.springframework.security.core.authority.SimpleGrantedAuthority;

import com.example.security.entity.SecurityUser;
import com.example.security.entity.UserRole;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import com.example.security.util.Constants;
public class JwtUtil {
	public static final String TOKEN_TYPE="Bearer";
	public static void main(String[] args) {
		String token="eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMDAxMCIsInNjb3BlIjpbeyJyb2xlSWQiOiIxIiwicm9sZU5hbWUiOiJST0xFX0FETUlOIn0seyJyb2xlSWQiOiIyIiwicm9sZU5hbWUiOiJST0xFX0NPTU1PTiJ9LHsicm9sZUlkIjoiMyIsInJvbGVOYW1lIjoiUk9MV19VU0VSUyJ9XSwiaXNzIjoiaHR0cDovL2ppYW5naHUuY29tIiwiaWF0IjoxNTM3Nzc3NjY0LCJleHAiOjE1Mzc3Nzk0NjR9.QXbt6loPeHMulR0D0lnm4GX8JN0J4j-SochtO12_Vmg";
		System.err.println(getRoles(token));
		List<Map<String, Object>> rolesList=getRoles(token);
		for(int i=0;i<rolesList.size();i++) {
    		Object role=rolesList.get(i);
    		if(role instanceof UserRole){
    			System.out.println("1111");
    		}

    	}
	}
	  public static List<Map<String, Object>> getRoles(String token) {
		  token=token.replaceAll(TOKEN_TYPE, "");
		  List<Map<String, Object>> roles=new ArrayList<>();
		  Claims claims=Jwts.parser()
	                .setSigningKey(Constants.SIGNING_KEY)
	                .parseClaimsJws(token.trim())
	                .getBody();
		   roles=(List<Map<String, Object>>) claims.get("scope");
		  return roles;
	    }

    public static  Claims getAllClaimsFromToken(String token) {
        return Jwts.parser()
                .setSigningKey(Constants.SIGNING_KEY)
                .parseClaimsJws(token.replace("Bearer ", ""))
                .getBody();
    }

	
	public static String generateToken(SecurityUser user) {
		String token=null;
		 Claims claims = Jwts.claims().setSubject(user.getUid());
	        //claims.put("scopes", Arrays.asList(new SimpleGrantedAuthority("ROLE_ADMIN")));
		 	claims.put("scope", user.getRoleList());
	        token= Jwts.builder()
	                .setClaims(claims)
	                .setIssuer("http://jianghu.com")
	                .setIssuedAt(new Date(System.currentTimeMillis()))
	                 .setExpiration(new Date(System.currentTimeMillis() +  30 * 60 * 1000)) // 设置过期时间 365 * 24 * 60 * 60秒(这里为了方便测试，所以设置了1年的过期时间，实际项目需要根据自己的情况修改)
	                .signWith(SignatureAlgorithm.HS256, Constants.SIGNING_KEY)
	                .compact();
		 return token;
	}

}
